package com.tanhua.dubbo.api.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.dubbo.api.TaoHuaApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.pojo.Audio;
import com.tanhua.dubbo.pojo.UserInfo;
import com.tanhua.dubbo.vo.AudioVo;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Calendar;
import java.util.concurrent.TimeUnit;

@DubboService(version = "1.0.0")
public class TaoHuaApiImpl implements TaoHuaApi {
    @Autowired
    protected FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;
    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;

    //用户发送次数的前缀
    private static final String SEND_AUDIO = "SEND_AUDIO_";

    //用户接受次数的前缀
    private static final String RECEPTION_AUDIO = "RECEPTION_AUDIO";
    long milliSecondsLeftToday = 86400000 - DateUtils.getFragmentInMilliseconds(Calendar.getInstance(), Calendar.DATE);

    //保存用户发送的语音
    @Override
    public String saveAudio(Audio audio) {
        Long userId = audio.getUserId();
        //判断用户是否还有次数
        String redisKey = SEND_AUDIO + userId;
        Integer count = Convert.toInt(redisTemplate.opsForHash().get(redisKey, "hash_" + userId));
        if (ObjectUtil.equal(count, 10)) {
            return null;
        }

        if (ObjectUtil.isEmpty(count)) {
            redisTemplate.opsForHash().put(redisKey, "hash_" + userId, "0");
            audio.setRemainingTimes(9);
        } else {
            audio.setRemainingTimes(10 - count);
        }
        UserInfo userInfo = userInfoApi.queryByUserId(audio.getUserId());
        audio.setAge(userInfo.getAge());
        audio.setId(ObjectId.get());
        audio.setAvatar(userInfo.getLogo());
        audio.setGender(userInfo.getSex().name().toLowerCase());
        audio.setNickname(userInfo.getNickName());

        mongoTemplate.save(audio);
        redisTemplate.opsForHash().increment(redisKey, "hash_" + userId, 1);
        redisTemplate.expire(redisKey, milliSecondsLeftToday, TimeUnit.MILLISECONDS);

        return "发送成功";
    }

    //接收语音
    @Override
    public AudioVo getAudio(Long userId) {
        Integer count = Convert.toInt(this.redisTemplate.opsForHash().get(RECEPTION_AUDIO + userId, "hash_" + userId));
        if (ObjectUtil.isEmpty(count)) {
            redisTemplate.opsForHash().put(RECEPTION_AUDIO + userId, "hash_" + userId, "1");
            count = 9;
        } else {
            count = 10 - count;
        }
        Query query = Query.query(Criteria.where("userId").nin(userId));
        Audio audio = mongoTemplate.findOne(query, Audio.class);

        if (ObjectUtil.isEmpty(audio) || count < 0) {
            AudioVo defultAudioVo = new AudioVo();
            defultAudioVo.setAvatar(audio.getAvatar());
            defultAudioVo.setNickname("admin");
            defultAudioVo.setGender(audio.getGender());
            defultAudioVo.setAge(99);
            defultAudioVo.setSoundUrl(audio.getSoundUrl());
            defultAudioVo.setRemainingTimes(0);
            defultAudioVo.setId(audio.getUserId());
            return defultAudioVo;
        }
        AudioVo audioVo = new AudioVo();
        BeanUtil.copyProperties(audio, audioVo, "remainingTimes");
        audioVo.setRemainingTimes(count);
        redisTemplate.opsForHash().increment(RECEPTION_AUDIO + userId, "hash_" + userId, 1);
        redisTemplate.expire(RECEPTION_AUDIO + userId, milliSecondsLeftToday, TimeUnit.MILLISECONDS);
        return audioVo;
    }
}

